<template>
  <div>
    <el-page-header
      icon="el-icon-arrow-left"
      @click="goTo(route.query.redirect)"
      content="发票信息"
    >
    </el-page-header>
    <el-upload
      class="upload-inv"
      :action="InvFullUploadUrl"
      :show-file-list="false"
      :headers="headers"
      :on-success="uploadSuccess"
      :on-error="uploadFail"
      :before-upload="beforeUpload"
      drag
      multiple
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击打开</em></div>
      <template #tip>
        <div class="el-upload__tip" type="error">
          支持JPG|PNG|PDF格式，单文件大小不超过5MB；可选择多个文件!
        </div>
      </template>
    </el-upload>
    <el-alert title="每份￥0.05,已存在或失败不计费!!!" type="warning" show-icon />
    <el-progress :percentage="percentage" v-if="percentage"></el-progress>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="24" style="text-align: right">
        <el-button
          type="primary"
          :size="'mini'"
          @click="DownloadAsExcelFile('invInfoTable')"
          v-if="invInfo.length > 0"
          >导出</el-button
        ><el-button
          type="primary"
          :size="'mini'"
          @click="goTo('/invoice/info/all', route.fullPath)"
          >我的发票</el-button
        ></el-col
      ></el-row
    >
    <el-table
      border
      :data="invInfo"
      :size="'mini'"
      :row-class-name="tableRowClassName"
      :max-height="winHeight"
      style="width: 100%"
      id="invInfoTable"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="fileName" label="文件名" sortable />
      <el-table-column prop="invCode" label="发票代码" sortable />
      <el-table-column prop="invNum" label="发票号码" sortable />
      <el-table-column prop="invDate" label="开票日期" sortable />
      <el-table-column prop="invMoney" label="开具金额" sortable />
      <el-table-column prop="invChk" label="验证码" width="180" sortable />
      <el-table-column prop="invTip" label="备注" sortable />
      <el-table-column
        v-for="(item, index) in colunmName"
        :key="index"
        :label="item"
        :prop="item"
      />
    </el-table>
  </div>
</template>

<script>
import { reactive, computed, ref } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import { InvFullUploadUrl, ApiGetUserAccount } from "@/http/api";
import { ElMessage } from "element-plus";
import { compressImage } from "@/libs/pic";
import { DownloadAsExcelFile } from "@/libs/download";
import { goTo } from "@/libs/utils";

export default {
  setup() {
    const route = useRoute();
    const store = useStore();
    //变量
    const invInfo = reactive([]);
    const headers = { token: store.state.token };
    const winHeight = ref(parseInt(window.innerHeight * 0.45));
    const progress = reactive({ total: 0, num: 0 });
    const colunmName = reactive([]);
    // onMounted(() => {
    //   ElNotification.warning("每份￥0.05,已存在或失败不计费!!!");
    // });
    //处理进度
    const percentage = computed(() =>
      progress.total ? Math.round((progress.num / progress.total) * 100) : null
    );
    //表格状态
    const tableRowClassName = ({ row }) => {
      let rowClass;
      if (row.status && row.code === 2000) {
        rowClass = "success";
      } else if (row.status && row.code === 5002) {
        rowClass = "exists";
      } else {
        rowClass = "failed";
      }
      return rowClass;
    };
    //上传成功
    const uploadSuccess = (res, file) => {
      progress.num += 1;
      if (res.code === 5004) {
        let invData = reactive({
          fileName: file.name,
          invTip: res.message,
          invCode: "",
          invNum: "",
          invDate: "",
          invMoney: "",
          invChk: "",
          status: false,
          code: "",
        });
        invInfo.push(invData);
      } else if (res.code !== 2000 && res.code !== 5002) {
        ElMessage.error(`文件${file.name}失败:${res.message}`);
      } else {
        let invData = reactive({});
        invData["fileName"] = file.name;
        invData["invTip"] = res.data.status ? res.message : res.data.message;
        invData["invCode"] = res.data.inv_code;
        invData["invNum"] = res.data.inv_num;
        invData["invDate"] = res.data.inv_date;
        invData["invMoney"] = res.data.inv_money || "";
        invData["invChk"] = res.data.inv_chk ? res.data.inv_chk.toString() : "";
        invData["status"] = res.data.status;
        invData["code"] = res.code;
        if (res.data.detail) {
          try {
            const detail = JSON.parse(res.data.detail);
            for (let cat in detail) {
              if (cat == "raw" || cat == "top") continue;
              for (let key in detail[cat]) {
                let vals = detail[cat][key];
                if (cat == "commodity") {
                  vals = "";
                  for (let idx in detail[cat][key]) {
                    vals = vals + detail[cat][key][idx].word + "\n";
                  }
                }
                invData[key] = vals;
                if (colunmName.indexOf(key) === -1) colunmName.push(key);
              }
            }
            invData["invTip"] = "全票面解析成功";
          } catch (err) {
            ElMessage.error("解析详情出错!");
          }
        }
        invInfo.push(invData);
      }
      //如果已经是最后一个文件，则更新账户余额
      if (progress.num === progress.total) {
        ApiGetUserAccount().then((res) => {
          if (res.code === 2000) {
            store.commit("setUserAmount", res.data.amount);
          } else {
            ElMessage.error(res.message);
          }
        });
      }
    };
    //上传失败
    const uploadFail = (err, file) => {
      progress.num += 1;
      ElMessage.error(`文件${file.name}提交失败:${err.message}`);
    };
    //上传之前: 文件格式、文件大小、进度等处理
    const beforeUpload = (file) => {
      const isPic = file.type === "image/jpeg" || "image/png";
      const isPdf = file.type === "application/pdf";
      const fileSize = file.size / 1024 / 1024;
      if (!isPic && !isPdf) {
        //是否合法格式
        ElMessage.error("上传文件只能是 JPG|PNG|PDF 格式!");
        return false;
      } else if (fileSize > 5) {
        //是否为大图片文件
        ElMessage.error(`文件${file.name}大小超出5MB限制!`);
        return false;
      } else if (isPic && fileSize > 1) {
        //大图片上传之前压缩
        progress.total += 1;
        return compressImage(file);
      } else {
        //正常文件
        progress.total += 1;
        return isPic || isPdf;
      }
    };

    return {
      colunmName,
      invInfo,
      InvFullUploadUrl,
      headers,
      percentage,
      winHeight,
      tableRowClassName,
      uploadSuccess,
      uploadFail,
      beforeUpload,
      DownloadAsExcelFile,
      goTo,
      route,
    };
  },
};
</script>

<style>
.el-table .failed {
  background: oldlace;
  color: #f56c6c;
}
.el-table .exists {
  color: #67c23a;
}
.el-table .success {
  background: #f0f9eb;
  color: #67c23a;
}
</style>